<template>
  <p>
    <a-space>
      <!--查询 - 日期、车次编号-->
      <a-date-picker v-model:value="keyword.date" valueFormat="YYYY-MM-DD" placeholder="请选择日期"/>
      <train-select v-model="keyword.code" width="200px"></train-select>
      <a-button type="primary" @click="handleQuery()">查找</a-button>
      <a-button type="primary" @click="onAdd">新增</a-button>
      <a-button type="danger" @click="onClickGenDaily">生成车次信息</a-button>
    </a-space>
  </p>
  <!--表格-->
  <a-table :dataSource="dailyTrains"
           :columns="columns"
           :pagination="pagination"
           @change="handleTableChange"
           :loading="loading">
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'operation'">
        <a-space>
          <a-popconfirm
              title="删除后不可恢复，确认删除?"
              @confirm="onDelete(record)"
              ok-text="确认" cancel-text="取消">
            <a style="color: red">删除</a>
          </a-popconfirm>
          <a @click="onEdit(record)">编辑</a>
        </a-space>
      </template>
      <template v-else-if="column.dataIndex === 'type'">
        <span v-for="item in TRAIN_TYPE_ARRAY" :key="item.code">
          <span v-if="item.code === record.type">
            {{ item.desc }}
          </span>
        </span>
      </template>
    </template>
  </a-table>
  <!--添加表单-->
  <a-modal v-model:visible="visible" title="每日车次" @ok="handleOk"
           ok-text="确认" cancel-text="取消">
    <a-form :model="dailyTrain" :label-col="{span: 5}" :wrapper-col="{ span: 20 }">
      <a-form-item label="日期">
        <a-date-picker v-model:value="dailyTrain.date" valueFormat="YYYY-MM-DD" placeholder="请选择日期"/>
      </a-form-item>
      <a-form-item label="车次编号">
        <train-select v-model="dailyTrain.code" @change="onChangeCode"></train-select>
      </a-form-item>
      <a-form-item label="车次类型">
        <a-select v-model:value="dailyTrain.type">
          <a-select-option v-for="item in TRAIN_TYPE_ARRAY" :key="item.code" :value="item.code">
            {{ item.desc }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="始发站">
        <a-input v-model:value="dailyTrain.start"/>
      </a-form-item>
      <a-form-item label="始发站拼音">
        <span class="station_py">{{ dailyTrain.startPinyin }}</span>
      </a-form-item>
      <a-form-item label="出发时间">
        <a-time-picker v-model:value="dailyTrain.startTime" format="HH:mm" valueFormat="HH:mm"
                       placeholder="请选择时间"/>
      </a-form-item>
      <a-form-item label="终点站">
        <a-input v-model:value="dailyTrain.end"/>
      </a-form-item>
      <a-form-item label="终点站拼音">
        <span class="station_py">{{ dailyTrain.endPinyin }}</span>
      </a-form-item>
      <a-form-item label="到站时间">
        <a-time-picker v-model:value="dailyTrain.endTime" format="HH:mm" valueFormat="HH:mm" placeholder="请选择时间"/>
      </a-form-item>
    </a-form>
  </a-modal>
  <a-modal v-model:visible="genDailyVisible" title="生成车次" @ok="handleGenDailyOk"
           :confirm-loading="genDailyLoading" ok-text="确认" cancel-text="取消">
    <a-form :model="genDaily" :label-col="{span: 4}" :wrapper-col="{ span: 20 }">
      <a-form-item label="日期">
        <a-date-picker v-model:value="genDaily.date" placeholder="请选择日期"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue';
import request from "@/utils/request";
import {notification} from 'ant-design-vue'
import {pinyin} from "pinyin-pro";
import TrainSelect from "@/components/TrainSelect.vue";
import dayjs from 'dayjs'

// 每日车次枚举
const TRAIN_TYPE_ARRAY = window.TRAIN_TYPE_ARRAY;
// 新增按钮隐藏属性
const visible = ref(false);
// 表格加载
let loading = ref(false);
// 添加每日车次的属性
let dailyTrain = ref({
  id: undefined,
  date: undefined,
  code: undefined,
  type: undefined,
  start: undefined,
  startPinyin: undefined,
  startTime: undefined,
  end: undefined,
  endPinyin: undefined,
  endTime: undefined,
});
// 表格数据
const dailyTrains = ref([]);
// 分页的三个属性名是固定的
const pagination = ref({
  position: ['bottomCenter'],
  total: 0,
  current: 1,
  pageSize: 8,
  showSizeChanger: true,
  pageSizeOptions: ['8', '15', '20']
});
// 表格展示列
const columns = [
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date',
  },
  {
    title: '车次编号',
    dataIndex: 'code',
    key: 'code',
  },
  {
    title: '车次类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '始发站',
    dataIndex: 'start',
    key: 'start',
  },
  {
    title: '始发站拼音',
    dataIndex: 'startPinyin',
    key: 'startPinyin',
  },
  {
    title: '出发时间',
    dataIndex: 'startTime',
    key: 'startTime',
  },
  {
    title: '终点站',
    dataIndex: 'end',
    key: 'end',
  },
  {
    title: '终点站拼音',
    dataIndex: 'endPinyin',
    key: 'endPinyin',
  },
  {
    title: '到站时间',
    dataIndex: 'endTime',
    key: 'endTime',
  },
  {
    title: '操作',
    dataIndex: 'operation'
  }
];

// 监视站名，转换拼音和首字母
watch(() => dailyTrain.value.start, () => {
  dailyTrain.value.startPinyin = Tool.isNotEmpty(dailyTrain.value.start)
      ? pinyin(dailyTrain.value.start, {toneType: 'none'}).replaceAll(" ", "")
      : dailyTrain.value.startPinyin = undefined;
}, {immediate: true});
watch(() => dailyTrain.value.end, () => {
  dailyTrain.value.endPinyin = Tool.isNotEmpty(dailyTrain.value.end)
      ? pinyin(dailyTrain.value.end, {toneType: 'none'}).replaceAll(" ", "")
      : dailyTrain.value.endPinyin = undefined;
}, {immediate: true});

// 点击添加按钮，表单显示
const onAdd = () => {
  dailyTrain.value = {};
  visible.value = true;
};

// 编辑每日车次
const onEdit = (record) => {
  dailyTrain.value = window.Tool.copy(record);
  visible.value = true;
};

// 删除每日车次
const onDelete = (record) => {
  request.delete(`/business/admin/daily-train/delete/${record.id}`)
      .then((result) => {
        if (result.status) {
          notification.success({description: result.message});
          handleQuery({
            pageNum: pagination.value.current,
            pageSize: pagination.value.pageSize,
          });
        } else {
          notification.error({description: result.message});
        }
      });
};

// 保存或者编辑时，选择车次；将车次数据合并
const onChangeCode = (obj) => {
  let t = Tool.copy(obj);
  delete t.id;
  // 用assign可以合并
  dailyTrain.value = Object.assign(dailyTrain.value, t);
};

// 请求 -- 保存每日车次
const handleOk = () => {
  request.post("/business/admin/daily-train/save", {
    ...dailyTrain.value,
    startTime: `${dailyTrain.value.startTime}:00`,
    endTime: `${dailyTrain.value.endTime}:00`
  })
      .then((result) => {
        if (result.status) {
          notification.success({description: result.message});
          visible.value = false;
          handleQuery({
            pageNum: pagination.value.current,
            pageSize: pagination.value.pageSize
          });
        } else {
          notification.error({description: result.message});
        }
      });
};

// 查询关键字 - 日期、车次编号
let keyword = ref({
  date: undefined,
  code: undefined
})
// 请求 -- 查询每日车次
const handleQuery = (param) => {
  // 如果无参，则查询当前页
  if (!param) {
    param = {
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize
    }
  }
  loading.value = true;
  request.get("/business/admin/daily-train/list", {
    params: {
      pageNum: param.pageNum,
      pageSize: param.pageSize,
      date: keyword.value.date,
      code: keyword.value.code
    }
  }).then((result) => {
    loading.value = false;
    if (result.status) {
      dailyTrains.value = result.content.records;
      // 设置分页控件的值
      pagination.value.current = param.pageNum;
      pagination.value.total = result.content.total;
    } else {
      notification.error({description: result.message});
    }
  });
};

// 生成每日车次的日期，并延后15天
const genDaily = ref({
  date: null
});
// 生成每日车次弹窗交互
const genDailyVisible = ref(false);
const genDailyLoading = ref(false);
const onClickGenDaily = () => {
  genDailyVisible.value = true;
};
// 请求 -- 生成每日车次数据
const handleGenDailyOk = () => {
  let date = dayjs(genDaily.value.date).format("YYYY-MM-DD");
  genDailyLoading.value = true;
  request.get(`/business/admin/daily-train/gen-daily/${date}`)
      .then(result => {
        genDailyLoading.value = false;
        if (result.status) {
          notification.success({description: result.message});
          genDailyVisible.value = false;
          handleQuery({
            pageNum: pagination.value.current,
            pageSize: pagination.value.pageSize
          });
        } else {
          notification.error({description: result.message});
        }
      });
};

// 表格换页，调用请求
const handleTableChange = (page) => {
  pagination.value = page
  handleQuery({
    pageNum: page.current,
    pageSize: page.pageSize,
  });
};

onMounted(() => {
  handleQuery({
    pageNum: 1,
    pageSize: pagination.value.pageSize
  });
});
</script>
